package com.sxp.dao.impl;

import com.sxp.bean.Book;
import com.sxp.bean.Cart;
import com.sxp.dao.CartDao;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;

import java.util.ArrayList;
import java.util.List;

/**
 * @author hsowan
 * @date 2019-06-14
 **/
public class CartDaoImpl implements CartDao {

    private SessionFactory factory = new Configuration().configure().buildSessionFactory();
    @Override
    public Integer save(Cart cart) {
        Transaction transaction = null;
        Integer orderId = null;
        try (Session session = factory.openSession()) {

            transaction = session.beginTransaction();
            orderId = (Integer) session.save(cart);
            transaction.commit();
        } catch (HibernateException e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
        return orderId;
    }

    @Override
    public Cart getByBookIdAndUserId(int bookId, int userId) {
        List result = null;
        try(Session session = factory.openSession()) {
            String hql = "from Cart as cart where cart.bookId = :bookId and cart.userId = : userId";
            Query query = session.createQuery(hql);
            query.setParameter("bookId", bookId);
            query.setParameter("userId", userId);
            result = query.list();
        } catch (HibernateException e) {
            e.printStackTrace();
        }
        if (result != null && result.size() == 1) {
            return (Cart) result.get(0);
        } else {
            return null;
        }
    }

    @Override
    public void update(Cart cart) {
        Transaction transaction = null;
        try (Session session = factory.openSession()) {
            transaction = session.beginTransaction();
            session.update(cart);
            transaction.commit();
        } catch (HibernateException e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
    }

    @Override
    public List<Cart> listByUserId(int userId) {
        String hql = "from Cart as cart where cart.userId = :userId";
        List<Cart> carts = new ArrayList<>();
        try(Session session = factory.openSession()) {
            Query query = session.createQuery(hql);
            query.setParameter("userId", userId);
            List result = query.list();
            for (Object cart: result) {
                carts.add((Cart) cart);
            }
        }
        return carts;
    }

}
